﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using Legazpi.Payroll.DataAccess.DataObjects;


namespace Legazpi.Payroll.Web.Helpers
{
    public static class Extensions
    {
        public static int ToInt(this string value)
        {
            int intValue;
            if (string.IsNullOrEmpty(value) || string.IsNullOrWhiteSpace(value))
                return 0;
            int.TryParse(value, out intValue);

            return intValue;
        }
        public static double ToDouble(this string value)
        {
            double dblValue;
            if (string.IsNullOrEmpty(value) || string.IsNullOrWhiteSpace(value))
                return 0.0;            
            double.TryParse(value, out dblValue);
            return dblValue;
        }

        public static string GetDescription(this Enum value)
        {
            if (!Enum.IsDefined(value.GetType(), value))
                return string.Empty;

            var descriptionAttribute = (DescriptionAttribute)value.GetType()
                .GetField(value.ToString())
                .GetCustomAttributes(false)
                .Where(a => a is DescriptionAttribute)
                .FirstOrDefault();

            return descriptionAttribute != null ? descriptionAttribute.Description : value.ToString();
        }

        public static double GetNoOfHours(this List<TimeRecord> records, int day)
        {
            if (records == null || records.Count == 0)
                return 0;

            var d = records.Where(x => x.Day == day).FirstOrDefault();

            return d != null ? d.TotalWorkHours : 0;
        }

        public static string GetTimeDisplay(this List<TimeRecord> records, int day, bool timeIn)
        {
            if (records == null || records.Count == 0)
                return string.Empty;

            var d = records.Where(x => x.Day == day).FirstOrDefault();
            if (d == null)
                return string.Empty;

            if (d.TimeIn.HasValue && d.TimeOut.HasValue)
            {
                if (d.TimeIn.Value == d.TimeOut.Value)
                    return string.Empty;
            }
            if (timeIn)
                return d != null && d.TimeIn.HasValue ? d.TimeIn.Value.ToString("HH:mm") : string.Empty;
            else
                return d != null && d.TimeOut.HasValue ? d.TimeOut.Value.ToString("HH:mm") : string.Empty;
        }

        public static string ToFormatDecimal(this double myNumber)
        {
            var s = string.Format("{0:0.00}", myNumber);

            if (s.EndsWith("00"))
            {
                return ((int)myNumber).ToString();
            }
            else
            {
                return s;
            }
        }
    }
}